#include <vector>
#include <string>
#include <cassert>
#include <iostream>
using namespace std;

class Solution 
{
public:
    bool exist(vector<vector<char> > &board, string word) 
	{
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		size_t m = board.size();
		if(m==0)
			return false;

		size_t n = board[0].size();
		if(n==0)
			return false;

		if(word.empty())
			return true;
		vector<vector<bool> > indicators(m);
		for(size_t i=0;i<m;i++)
			indicators[i] = vector<bool>(n,false);

		for(size_t i=0;i<m;i++)
		{
			for(size_t j=0;j<n;j++)
			{
				if(word[0]==board[i][j] && !indicators[i][j] && exist(board,i,j,word,0,indicators))
					return true;
			}
		}

		return false;
    }

private:
	bool exist(const vector<vector<char> >& board, size_t posx, size_t posy, const string& word,size_t curIdx,vector<vector<bool> >& indicators)
	{
		assert(board[posx][posy] == word[curIdx] && !indicators[posx][posy]);
		
		indicators[posx][posy] = true;
		if(curIdx>= word.size()-1)
			return true;

		if(posx>0 && board[posx-1][posy]==word[curIdx+1] && !indicators[posx-1][posy] && exist(board,posx-1,posy,word,curIdx+1,indicators))
			return true;

		if(posx<(board.size()-1) && board[posx+1][posy]==word[curIdx+1] && !indicators[posx+1][posy] && exist(board,posx+1,posy,word,curIdx+1,indicators))
			return true;

		if(posy>0 && board[posx][posy-1]==word[curIdx+1] && !indicators[posx][posy-1] && exist(board,posx,posy-1,word,curIdx+1,indicators))
			return true;

		if(posy<(board[posx].size()-1) && board[posx][posy+1]==word[curIdx+1] && !indicators[posx][posy+1] &&exist(board,posx,posy+1,word,curIdx+1,indicators))
			return true;

		indicators[posx][posy] = false;
		return false;
	}
};

int main()
{
	int m,n;
	Solution s;
	while(cin>>m)
	{
		if(m==0)
			break;
		cin>>n;
		while(cin.get() != '\n');

		vector<vector<char> > board(m);
		string line;
		for(int i=0;i<m;i++)
		{
			getline(cin,line);
			board[i] = vector<char>(line.begin(),line.end());
		}

		while(getline(cin,line))
		{
			if(line=="")
				break;
			cout<<s.exist(board,line)<<endl;
		}
	}
}